package com.yhsimon.realm.member.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yhsimon.realm.member.constant.ResultCodeEnum;
import com.yhsimon.realm.member.dto.user.UserDto;
import com.yhsimon.realm.member.entity.user.LoginRecordEntity;
import com.yhsimon.realm.member.service.LoginRecordService;
import com.yhsimon.realm.member.utils.AuthContextUtils;
import com.yhsimon.realm.member.utils.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private LoginRecordService loginRecordService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求方式
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {// 如果是跨域预检请求，直接放行

            return true;
        }

        // 获取token
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            responseNoLoginInfo(response);
            return false;
        }
        // 如果token不为空，那么此时验证token的合法性
        String sysUserInfoJson = redisTemplate.opsForValue().get("user:login:" + token);
        if (StrUtil.isEmpty(sysUserInfoJson)) {
            responseNoLoginInfo(response);
            return false;
        }
        // 若合法，将用户数据存储到ThreadLocal中
        UserDto userInfo = JSON.parseObject(sysUserInfoJson, UserDto.class);
        AuthContextUtils.setUserInfo(userInfo);
        // 重置 Redis中的用户数据的有效时间
        redisTemplate.expire("user:login:" + token, 30, TimeUnit.MINUTES);

        // 用户登录信息记录
        String remoteAddr = "";
        // 如果服务在容器后面有代理服务器（如Nginx、Apache等），那么原始的客户端IP可能会在请求头X-FORWARDED-FOR中
        remoteAddr = request.getHeader("X-FORWARDED-FOR");
        if (remoteAddr == null || "".equals(remoteAddr)) {
            remoteAddr = request.getRemoteAddr();
        }
        if (userInfo != null) {
            List<LoginRecordEntity> loginRecordEntityList = loginRecordService.list(new QueryWrapper<LoginRecordEntity>().eq("user_id", userInfo.getId()).eq("token", token));
            if(loginRecordEntityList==null||loginRecordEntityList.isEmpty()){
                log.info("登录名: {}", userInfo.getUsername());
                log.info("访问IP: {}", remoteAddr);
                log.info("用户代理: {}", request.getHeader("User-Agent"));
                log.info("登录时间： {}", LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
                LoginRecordEntity loginRecordEntity = new LoginRecordEntity();
                loginRecordEntity.setUserId(userInfo.getId());
                loginRecordEntity.setUsername(userInfo.getUsername());
                loginRecordEntity.setToken(token);
                loginRecordEntity.setRemoteAddr(remoteAddr);
                loginRecordEntity.setUserAgent(request.getHeader("User-Agent"));
                loginRecordService.save(loginRecordEntity);
            }
        }
        // 放行
        return true;
    }

    // 响应208 状态码给 前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        R result = R.error(ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtils.removeUserInfo(); // 所有操作完成后需要移除threadLocal中的数据
    }
}
